import {View, Text, StyleSheet, Image, TextInput, TouchableOpacityComponent, TouchableOpacity} from 'react-native'
import React, {Component} from 'react'
import LabelCellWithRightComp from "../../component/widget/labelCellWithRightComp";
import {AppIcon} from "../../assets/icon/AppIcon";
import {margin, default as styles, roundWithSize, rectWithSize, padding} from "../../style";
import {Actions} from "react-native-router-flux";
import {inject, observer} from "mobx-react/custom";
import {Store} from "../../store";
import showPicker from "../../component/common/PickerProxy";
import {UserModelInterface} from "../../net/instance/CommenModelInstance";
import * as _ from 'lodash'
import {dateFormat, defaultObj, getAssetUrl} from "../../util";
import moment from 'moment';
import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view";
import FastImageCustom from "../../component/widget/FastImageCustom";
import {showImagePicker} from "../../component/common/ImagePickerProxy";
import {uploadFile} from "../../net";
import FastImage from "react-native-fast-image";

interface ProfileSettingProps extends Store {

}

interface ProfileSettingState extends UserModelInterface {

}

const placeholderAvatar = require("../../assets/img/avatar_placeholder.png");


export default class ProfileSettingWrapper extends Component<ProfileSettingProps, ProfileSettingState> {
    static onRight() {
        const wrapper: ProfileSettingWrapper = Actions.refs["ProfileSetting"];
        const instance: ProfileSetting = wrapper.profileSetting["wrappedInstance"];
        instance.onSave();
    }

    profileSetting: ProfileSetting;

    render() {
        return <ProfileSetting ref={profileSetting => this.profileSetting = profileSetting}/>;
    }
}

@inject("user")
@observer
class ProfileSetting extends Component<ProfileSettingProps, ProfileSettingState> {
    state: ProfileSettingState = defaultObj;

    constructor(props: ProfileSettingProps) {
        super(props);

    }

    onSave = async () => {
        await this.props.user.updateUserInfo(this.state);
        global.showSuccess("更新成功！");
    };


    async componentDidMount() {
        await this.props.user.refreshUserData();
        this.setState(_.cloneDeep(this.props.user.user))
    }

    chooseGender = () => {
        const {gender} = this.state;
        showPicker<string>({
            pickerData: ["男", "女"],
            selectedValue: [gender ? "男" : "女"],
            onPickerConfirm: data => {
                this.setState({
                    gender: data[0] === "男" ? 1 : 0
                })
            }
        })
    };
    chooseBirthday = () => {
        const {birthday} = this.state;
        const selectedValue: string[] = dateFormat(birthday, "YYYY年-MM月-DD日").split("-");
        showPicker<string>({
            pickerData: require("../../assets/json/date.json"),
            selectedValue,
            onPickerConfirm: data => {
                function removeSparator(str) {
                    return +str.replace(/(年|月|日)/g, "");
                }

                const birthday = moment();
                birthday.year(removeSparator(data[0])).month(removeSparator(data[1])).date(removeSparator(data[2]));
                console.log(birthday);
                this.setState({
                    birthday: birthday.toDate()
                })
            }
        })
    };
    textInputChange = (key: string) => {
        return (text: string) => {
            const state: any = {
                [key]: text
            };
            this.setState(state);
        }
    };

    uploadAvatarImage = async () => {

        const res = await showImagePicker(), {uri, fileName="defalut.JPG"} = res;
        const file = await uploadFile(uri, fileName);
        this.setState({
            avatarUrl: getAssetUrl(file)
        });
        global.showSuccess("上传成功!");
    };
    logOut = async ()=>{
        await this.props.user.logOut();
        Actions.reset("Login");
    };

    render() {
        const {avatarUrl, nickName, gender, birthday, phone} = this.state;
        const imageData = avatarUrl ? {uri: avatarUrl} : placeholderAvatar;

        return (<KeyboardAwareScrollView style={style.container}>
            <LabelCellWithRightComp onPress={() => {
                Actions.push("AddressManage")
            }} label={{text: "收货地址"}} style={margin(8, 0)}
                                    rightCmp={<AppIcon name={"youjiantou"} size={16} color={"#999"}/>}/>

            <LabelCellWithRightComp label={{text: "头像"}}
                                    rightCmp={
                                        <TouchableOpacity activeOpacity={.8} onPress={this.uploadAvatarImage}>
                                            <FastImage
                                                style={roundWithSize(50)}
                                                resizeMode={"contain"}
                                                source={imageData}/>
                                        </TouchableOpacity>
                                    }/>

            <LabelCellWithRightComp label={{text: "昵称"}}
                                    rightCmp={<View style={[styles.flexDirectionRowNotFlex, styles.centerH]}>
                                        <TextInput underlineColorAndroid={"transparent"}
                                                   onChangeText={this.textInputChange("nickName")}
                                                   style={[{
                                                       fontSize: 14,
                                                       color: "#666",
                                                       marginRight: 6,
                                                       paddingLeft: 10
                                                   }, padding(0)]}
                                                   defaultValue={nickName}/>
                                    </View>}/>
            <LabelCellWithRightComp label={{text: "性别"}}
                                    onPress={this.chooseGender}
                                    rightCmp={<View style={[styles.flexDirectionRowNotFlex, styles.centerH]}>
                                        <Text style={{
                                            fontSize: 14,
                                            color: "#666",
                                            marginRight: 6
                                        }}>{gender ? "男" : "女"}</Text>
                                        <AppIcon name={"youjiantou"} size={16} color={"#999"}/>
                                    </View>}/>
            <LabelCellWithRightComp label={{text: "生日"}}
                                    onPress={this.chooseBirthday}
                                    rightCmp={<Text style={{
                                        fontSize: 14,
                                        color: "#666"
                                    }}>{dateFormat(birthday, "YYYY年MM月DD日")}</Text>}/>
            {/*<LabelCellWithRightComp label={{text: "手机"}}*/}
                                    {/*rightCmp={<TextInput underlineColorAndroid={"transparent"}*/}
                                                         {/*style={[{fontSize: 14, color: "#666"}, padding(0)]}*/}
                                                         {/*onChangeText={this.textInputChange("phone")}*/}
                                                         {/*defaultValue={phone}/>}/>*/}
            <TouchableOpacity style={style.signOutBtn} onPress={this.logOut}>
                <Text style={style.signOutText}>退出账号</Text>
            </TouchableOpacity>
        </KeyboardAwareScrollView>)
    }
}

const style = StyleSheet.create({
    container: {},
    signOutBtn: {
        marginTop: 30,
        backgroundColor: "#fff",
        paddingVertical: 15,
        alignItems: "center",
        justifyContent: "center",
    },
    signOutText: {
        color: "red",
        fontSize: 14
    }
});

 